﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Xml.Linq;

namespace Songhay.Net
{
    using Collections;
    using Extensions;
    using Models;
    using Xml;

    /// <summary>
    /// Static helpers for <see cref="RemoteResource"/>.
    /// </summary>
    public static class RemoteResourceAsyncUtility
    {
        /// <summary>
        /// Lists the IIS directory.
        /// </summary>
        /// <param name="directoryUri">The directory URI.</param>
        /// <param name="listReadyAction">The list ready action.</param>
        public static void ListIISDirectory(Uri directoryUri, Action<RemoteResourceCollection> listReadyAction)
        {
            ListIISDirectory(directoryUri, null, listReadyAction);
        }

        /// <summary>
        /// Lists the IIS directory.
        /// </summary>
        /// <param name="directoryUri">The directory URI.</param>
        /// <param name="baseUriOfOutput">The base URI of output.</param>
        /// <param name="listReadyAction">The list ready action.</param>
        public static void ListIISDirectory(Uri directoryUri, Uri baseUriOfOutput, Action<RemoteResourceCollection> listReadyAction)
        {
            if(directoryUri == null) throw new ArgumentNullException("directoryUri", "The URI is null.");
            if(listReadyAction == null) throw new ArgumentNullException("listReadyAction", "The action is null.");
            if(baseUriOfOutput == null)
            {
                baseUriOfOutput = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}",
                    directoryUri.Scheme, directoryUri.Host, directoryUri.Port));
            }

            HttpVerbAsyncUtility.Get(directoryUri, new Action<object, DownloadStringCompletedEventArgs>((sender, args) =>
            {
                var s = args.Result;
                s = HtmlUtility.ConvertToXml(s);
                s = s.Replace("<A", "<a");
                s = s.Replace("</A>", "</a>");
                s = s.Replace("HREF=", "href=");

                if(string.IsNullOrEmpty(s)) return;

                var x = XDocument.Parse(s);
                var collection = new RemoteResourceCollection();

                if(x.Descendants("a").Count() == 0) return;
                if(x.Descendants("a").Attributes("href").Count() == 0) return;

                x.Descendants("a").Where(a => a.Value.Contains(".xaml")).ForEachInEnumerable(d =>
                {
                    s = d.Attribute("href").Value;
                    if(s.StartsWith("/")) s = s.Remove(0, 1);
                    s = string.Concat(baseUriOfOutput.AbsoluteUri, s);
                    var location = new Uri(s, UriKind.Absolute);
                    var segments = location.AbsoluteUri.Split('/');
                    var displayName = segments.Last();
                    displayName = displayName.Replace(".xaml", string.Empty);
                    displayName = displayName.Replace("%20", " ");
                    var resource = new RemoteResource { DisplayName = displayName, Location = location };
                    collection.Add(resource);
                });

                listReadyAction(collection);

            }));
        }
    }
}
